<?php
class wiki
{
	var $db;
	var $table;
	var $table_log;
	var $ishtml = 0;
	var $userid = 0;
	var $userid_sql = '';
	var $pages;
	var $number;
	var $url;
	var $html;
	var $s;
	var $is_update_related = 1;

    function __construct()
    {
		global $db, $log, $MODULE;
		$this->db = &$db;
		$this->table = DB_PRE.'wiki';
		//$this->table_tag = DB_PRE.'wiki_tag';
		//$this->log = is_object($log) ? $log : load('log.class.php','log');
		//$this->url = load('url.class.php','url');
		
		$this->attachment = is_object($attachment) ? $attachment : load('attachment.class.php', 'attachment');
		$this->search = is_object($search) ? $search : load('search.class.php', 'search');
		$this->html = is_object($html) ? $html : load('html.class.php', 'html');
		$this->comment = is_object($comment) ? $comment : load('comment.class.php', 'comment');
		$this->pay = is_object($pay) ? $pay : load('pay_api.class.php', 'pay');
		$this->credit = is_object($credit) ? $credit : load('credit.class.php','credit');
		$this->feed = is_object($feed) ? $feed : load('feed.class.php', 'feed');
		
		
    }

	function wiki()
	{
		$this->__construct();
	}
	
	function set_userid($userid)
	{
		$this->userid = intval($userid);
		$this->userid_sql = " AND $this->table.`userid`=$this->userid ";
	}

	function get($wikiid, $tablecount = 2)
	{
		$wikiid = intval($wikiid);
		$data = $this->db->get_one("SELECT * FROM `$this->table` WHERE `wikiid`=$wikiid $this->userid_sql");
		return $data;
	}

	function add($data, $cat_selected = 0, $isimport = 0)
	{ 
		global $_userid, $_username,$CATEGORY, $MODEL, $SETTING;
		
		require_once 'model/wiki_input.class.php';
        require_once 'model/wiki_update.class.php';
		$wiki_input = new wiki_input();
		$inputinfo = $wiki_input->get($data, $isimport);
		
		$systeminfo = $inputinfo['system'];
		$modelinfo = $inputinfo['model'];
		if(!$systeminfo['username']) $systeminfo['username'] = $_username;
		if(!$systeminfo['userid']) $systeminfo['userid'] = $_userid;

		if($data['inputtime'])
		{
			$systeminfo['inputtime'] = strtotime($data['inputtime']);
		}
		else
		{
			$systeminfo['inputtime'] = TIME;
		}
		if($data['updatetime'])
		{
			$systeminfo['updatetime'] = strtotime($data['updatetime']);
		}
		else
		{
			$systeminfo['updatetime'] = TIME;
		}
	
		$this->db->insert($this->table, $systeminfo);
		$wikiid = $this->db->insert_id();
	
		
		// 内容页地址
		$url = $data['islink']==1 ? $data['linkurl'] : $this->url($wikiid, 0, $systeminfo['inputtime'], $data['prefix']);
        $this->db->query("UPDATE `$this->table` SET `url`='$url' WHERE `wikiid`=$wikiid");
		
		/*添加积分*/
		$this->credit->update($_userid,  $_username, $point=10, 0);
		$this->pay->update_exchange('wiki', 'point', /*'-'.*/$point=10, '描述');
		
		/*产生feed*/
		$this->feed->add('wiki','wikiid',$wikiid);
		
		/*搜索*/
		$this->search_api($wikiid);
		
		return $wikiid;
	}

	function edit($wikiid, $data)
	{
		global $MODEL,$SETTING;
 
		
		require_once 'model/wiki_input.class.php';
        require_once 'model/wiki_update.class.php';
		$this->is_update_related = 0;

		$wiki_input = new wiki_input();
		$inputinfo = $wiki_input->get($data);
		$systeminfo = $inputinfo['system'];
		$modelinfo = $inputinfo['model'];
		
		if(isset($data['paginationtype']))
		{
			$modelinfo['paginationtype'] = $data['paginationtype'];
			$modelinfo['maxcharperpage'] = $data['maxcharperpage'];
		}
		if($data['inputtime'])
		{
			$systeminfo['inputtime'] = strtotime($data['inputtime']);
		}
		else
		{
			$systeminfo['inputtime'] = TIME;
		}
		$systeminfo['updatetime'] = TIME;
		
		
		// 内容详细地址设置
		if($data['islink']==1)
		{
			$systeminfo['url'] = $data['linkurl'];
		}
		else
		{
			/*$prefix = $data['prefix'] ? $data['prefix'] : ($SETTING['enable_urlencode'] ? hash_string($wikiid) : '');*/
			
			$systeminfo['url'] = $this->url($wikiid, 0, $systeminfo['inputtime'], $data['prefix']);

		}	
		$this->db->update($this->table, $systeminfo, "`wikiid`=$wikiid $this->userid_sql");
		unset($systeminfo['status']);
		//if($modelinfo) $this->db->update($this->model_table, $modelinfo, "`wikiid`=$wikiid");
		$wiki_update = new wiki_update($wikiid);
		$wiki_update->update($data);
		
		
		
		// 如果栏目设置是静态化，这里生成静态页 $leotyn
		//$html = load('html.class.php','html');
		//$html->show($wikiid);
		
		//$this->html($wikiid);

		//$this->log_write($wikiid, '', '', $data['islink']);
		return true;
	}

	function listinfo($where = '', $order = '`listorder` DESC,`wikiid` DESC', $page = 1, $pagesize = 50)
	{
		//if($where) $where = " WHERE $where $this->userid_sql";
		
		// 指定会员发布的文章列表 aming
		if($this->userid){
			$where = $where ? " WHERE $where AND $this->table.`userid`=$this->userid " : " WHERE $this->table.`userid`=$this->userid ";
		}
		else{
			$where = " WHERE $where ";
		}
		
		if($order) $order = " ORDER BY $order";
		$page = max(intval($page), 1);
        $offset = $pagesize*($page-1);
        $limit = " LIMIT $offset, $pagesize";
        $number = cache_count("SELECT count(*) AS `count` FROM `$this->table` $where");
		
        $this->pages = pages($number, $page, $pagesize);
		$array = array();
		$result = $this->db->query("SELECT * FROM `$this->table` $where $order $limit");
		while($r = $this->db->fetch_array($result))
		{
		    $r['inputtime'] = $r['inputtime'];
		    $r['updatetime'] = $r['updatetime'];
			$array[] = $r;
		}
		$this->number = $this->db->num_rows($result);
        $this->db->free_result($result);
		return $array;
	}

	function listorder($info)
	{
		if(!is_array($info)) return false;
		foreach($info as $id=>$listorder)
		{
			$id = intval($id);
			$listorder = intval($listorder);
			$this->db->query("UPDATE `$this->table` SET `listorder`=$listorder WHERE `wikiid`=$id $this->userid_sql");
			$this->log_write($id, 'listorder');
		}
		return true;
	}

	/*function search($sql, $page = 1, $pagesize = 20, $setting = array())
	{
		$page = max(intval($page), 1);
		$offset = $number*($page-1);
		$sql_count = preg_replace("/^SELECT([^(]+)FROM(.+)(ORDER BY.+)$/i", "SELECT COUNT(*) AS `count` FROM\\2", $sql);
		$count = cache_count($sql_count);
		$this->pages = pages($count, $page, $number);
		$data = array();
		$result = $db->query("$sql LIMIT $offset, $number");
		while($r = $db->fetch_array($result))
		{
			$data[] = $r;
		}
		$db->free_result($result);
		return $data;
	}*/

	function output($data)
	{
		require_once 'model/wiki_output.class.php';
		$output = new wiki_output();
		return $output->get($data);
	}

	function log_write($wikiid, $handle = '', $is_admin = 0, $islink = 99)
	{
		if($is_admin) $this->ishtml = 1;
		if(!isset($islink)) $islink = 99;
		if($this->ishtml && ($handle == '' || $handle == 99))
		{
			if(!is_object($this->html)) $this->html = load('html.class.php','html');
			if($islink==99) $this->html->show($wikiid, $this->is_update_related);
		}
		$this->search_api($wikiid);
		//$this->log->set('wikiid', $wikiid);
		//return $this->log->add();
	}

	function search_api($wikiid)
	{
		global $MODULE,$MODEL,$CATEGORY;
		if(!isset($MODULE['search'])) return false;
		
		$r = $this->get($wikiid);
		if(!$r) return false;
	
	
        
		$this->search->set_type($type);
		if($r['searchid'])
		{
			if($r['status'] == 99)
			{
				$fulltext_array = require('model/wiki_fields.inc.php');
				foreach($fulltext_array AS $key=>$value)
				{
					if($value['isfulltext']) $fulltextwiki .= $r[$key].' ';
				}
				$this->search->update($r['searchid'], $r['title'], $fulltextwiki, $r['url']);
			}
			else
			{
				$this->search->delete($r['searchid']);
			}
		}
		elseif($r['status']==99)
		{
			$fulltext_array = require('model/wiki_fields.inc.php');
			foreach($fulltext_array AS $key=>$value)
			{
				//if($value['isfulltext']) $fulltextwiki .= $r[$key].' ';
			}
			$searchid = $this->search->add($r['title'], $fulltextwiki, $r['url']);
			if(!$searchid) return false;
            $this->db->query("UPDATE `$this->table` SET `searchid`=$searchid WHERE `wikiid`=$wikiid");
		}
		return true;
	}

    function wikiid($wikiid, $userid = 0, $allow_status = array())
    {
		$where = "`wikiid` IN(".implodeids($wikiid).")";
		$where .= $allow_status ? " AND `status` IN(".implodeids($allow_status).")" : '';
		$where .=  $this->userid_sql;
		$array = array();
		$result = $this->db->query("SELECT `wikiid` FROM `$this->table` WHERE $where");
		while($r = $this->db->fetch_array($result))
		{
			$array[] = $r['wikiid'];
		}
        $this->db->free_result($result);
		return is_array($wikiid) ? $array : $array[0];
    }

	function delete($wikiid)
	{
		global $MODULE;
		if(is_array($wikiid))
		{
			array_map(array(&$this, 'delete'), $wikiid);
		}
		else
		{
			$wikiid = intval($wikiid);
			$data = $this->db->get_one("SELECT `url`,`searchid` FROM `$this->table` WHERE `wikiid`=$wikiid $this->userid_sql");
			if($data)
			{
				if($this->ishtml) 
				{
					$html = load('html.class.php','html');
					//$html->delete($wikiid, $this->model_table);
				}
				
				$this->db->query("DELETE `$this->table` FROM `$this->table` WHERE $this->table.wikiid=$wikiid $this->userid_sql");
				
				if($this->db->affected_rows())
				{
					//$this->db->query("DELETE FROM `$this->table_count` WHERE `wikiid`=$wikiid");
					//$this->db->query("DELETE FROM `$this->table_position` WHERE `wikiid`=$wikiid");
					//$this->db->query("DELETE FROM `$this->table_tag` WHERE `wikiid`=$wikiid");
					
					// 删除相关附件 
					$this->attachment->delete("`wikiid`=$wikiid");
					
					// 删除相关评论
					$this->comment->delete(" `module`='$module' AND `field` = 'wikiid' AND `value` = '$wikiid' ");
					
					// 删除搜索检索
					$this->search->delete($data['searchid']);
					
					// 删除相关搜藏
					$this->collect->delete(" `module`='$module' AND `field` = 'wikiid' AND `value` = '$wikiid' ");
				}
				$this->log_write($wikiid, 'delete');
			}
		}
		return true;
	}

	function clear()
	{
		@set_time_limit(600);
		$result = $this->db->query("SELECT `wikiid` FROM `$this->table` WHERE `status`=0");
		while($r = $this->db->fetch_array($result))
		{
			$this->delete($r['wikiid']);
		}
        $this->db->free_result($result);
		return true;
	}

	function restore($wikiid)
	{
		return $this->status($wikiid, 99);
	}

	function restoreall()
	{
		@set_time_limit(600);
		$result = $this->db->query("SELECT `wikiid` FROM `$this->table` WHERE `status`=0");
		while($r = $this->db->fetch_array($result))
		{
			$this->status($r['wikiid'], 99);
		}
        $this->db->free_result($result);
		return true;
	}

	function count($where = '')
	{
		if($where) $where = " WHERE $where $this->userid_sql";
		return cache_count("SELECT count(*) AS `count` FROM `$this->table` $where");
	}

	function get_count($wikiid)
	{
		$wikiid = intval($wikiid);
		return $this->db->get_one("SELECT * FROM `$this->table` WHERE `wikiid`=$wikiid");
	}

	function hits($wikiid)
	{
		$wikiid = intval($wikiid);
		$r = $this->db->get_one("SELECT * FROM `$this->table` WHERE `wikiid`=$wikiid");
		if(!$r) return false;
		$hits = $r['hits'] + 1;
        return $this->db->query("UPDATE `$this->table` SET `hits`=$hits WHERE `wikiid`=$wikiid");
	}

	// 更新文章的状态
	function status($wikiid, $status, $is_admin = 0)
	{
		global $MODULE, $presentpoint;
		if(!$wikiid) return false;
		$status = intval($status);
		$wikiids = implodeids($wikiid);
		$is_update = $this->db->query("UPDATE `$this->table` SET `status`=$status WHERE `wikiid` IN($wikiids) $this->userid_sql");
		
		return $is_update;
	}

	function get_wikiid($title)
	{
		$info = $this->db->get_one("SELECT `wikiid` FROM `$this->table` WHERE `title`='$title'");
		if($info['wikiid']) return TRUE;
		else return FALSE;
	}

	function get_status($processid)
	{
		$processid = intval($processid);
		$array = array();
		$result = $this->db->query("SELECT `status` FROM `".DB_PRE."process_status` WHERE `processid`=$processid");
		while($r = $this->db->fetch_array($result))
		{
			$array[] = $r['status'];
		}
        $this->db->free_result($result);
		return $array;
	}

	function get_posid($wikiid = 0, $posid = 0)
	{
		return $this->db->get_one("SELECT * FROM `".DB_PRE."wiki` WHERE `wikiid`=$wikiid AND `posid`=$posid");
	}

	function add_posid($wikiid = 0, $posid = 0)
	{
		$wikiid = intval($wikiid);
		$posid = intval($posid);
		if(!$wikiid || !$posid) return false;
		//$this->db->query("INSERT INTO `".DB_PRE."wiki` (`posid`) VALUES ('$posid')");
		$this->db->query("UPDATE `".DB_PRE."wiki` SET `posid`= $posid WHERE `wikiid`=$wikiid");
		return true;
	}

	function add_typeid($wikiid = 0, $typeid = 0)
	{
		$wikiid = intval($wikiid);
		$typeid = intval($typeid);
		if(!$wikiid || !$typeid) return false;
		$this->db->query("UPDATE $this->table SET `typeid`=$typeid WHERE `wikiid`=$wikiid");
		return true;
	}

	function update_search($i)
	{
		$info = $this->db->get_one("SELECT `wikiid` FROM `$this->table` WHERE `status`=99 ORDER BY `wikiid` DESC LIMIT $i, 1");
		$this->search_api($info['wikiid']);
		return true;
	}

	function inspect($wikiid, $passname = '')
	{
		global $MODEL;
		if(!$passname) return false;
		require_once MOD_ROOT.'process/process.class.php';
		if(is_array($wikiid))
		{
			//...
		}
		return true;
	}

	function get_pro_status()
	{
		global $priv_role;
		$status = array();
		$STATUS = $this->db->select("SELECT `status`, `name` FROM `".DB_PRE."status` WHERE `status`>2 AND `status`!=99");
		foreach($STATUS as $S)
		{
			$process = $this->db->select("SELECT `processid` FROM `".DB_PRE."process_status` WHERE `status`=$S[status]");
			foreach($process as $p)
			{
				if($priv_role->check('processid', $p['processid']))
				{
					$status[] = $S;
					break;
				}
			}
		}
		return $status;
	}
	
	function html($wikiid, $is_update_related = 0)
	{
		global $MODEL,$CATEGORY;
		require_once 'wiki.class.php';
		$wiki = new wiki();
		$r = $wiki->get($wikiid);
		//if(!$r) return false;
		
		
		$data = $wiki->output($r);
		extract($data);
		
		$head['keywords'] = str_replace(' ', ',', $r['keywords']);
		$head['description'] = $r['description'];
		
		
		$pages = $titles = '';
	
		$page = $page ? $page : 1;
		
	
		$title = strip_tags($title);
		$head['title'] = $title.'_'.$C['catname'].'_'.$SETTING['sitename'];
		$ishtml = 1;
		$url = $this->url($r['wikiid'], 0, $r['inputtime'],$prefix);
		
		ob_start();
		
		include template('view.html','wiki');
		return createhtml($url);
	}
	
	function url($wikiid, $page = 0, $time = 0, $prefix = '')
	{
		global $SETTING;
		if($SETTING['ishtml']){
			$wikiid = $prefix ? $prefix : $wikiid;
			$url = $page ? "wiki/{$wikiid},{$page}.{$SETTING['fileext']}" : "wiki/{$wikiid}.{$SETTING['fileext']}";
		}
		else{
			// 内容页的动态地址
			//$url = $page ? "./?show/{$wikiid},{$page}.{$SETTING['fileext']}" : "./?show/{$wikiid}.{$SETTING['fileext']}";
			$url = $page ? "?module=wiki&wikiid={$wikiid}&page={$page}" : "?module=wiki&wikiid={$wikiid}";
		}
		return $url;
	}
	
	//产生feed
	/*function feed($id){
		include_once(MOD_ROOT.'feed/feed.class.php');
		$feed = new feed();
		$feed->add('wiki','wikiid',$id);
	}*/
}
?>